import axios from 'axios';
const $axios = axios.create();

$axios.interceptors.request.use(config => {
  if (config.data && config.data.params) {
    const params = config.data.params;
    if (typeof params === 'object') {
      for (const index in params) {
        if (typeof params[index] === 'string') {
          params[index] = params[index].trim();
        }
      }
    }
  }
  if (config.method == 'get') {
    if (config.url.indexOf('?') > -1) {
      config.url = `${config.url}&random=${Math.random()}`;
    } else {
      config.url = `${config.url}?random=${Math.random()}`;
    }
  }
  config.headers.crctoken = window.sessionStorage.getItem('crctoken') || '';
  return config;
}, error => {
  return Promise.reject(error);
});

$axios.interceptors.response.use(response => {
  return response;
}, error => {
  // 请求超时
  if (error.message.indexOf('timeout of') === 0) {
    return Promise.reject({
      message: '业务繁忙，请稍后重试',
      code: -1
    });
  }
  return Promise.reject(error);
});

const http = (method, url, params = {}) => {
  const httpDefault = {
    method,
    url,
    params: method === 'GET' ? params : null,
    data: method === 'POST' ? params : null,
    timeout: 1000 * 60
  };
  return new Promise((resolve, reject) => {
    $axios(httpDefault).then(res => {
      resolve(res);
    }).catch(error => {
      if (error.message.indexOf('401') < 0) { reject(error); }
    });
  });
};

const fetchPost = (url, params) => {
  return http('POST', url, params);
};

const fetchGet = (url, params) => {
  return http('GET', url, params);
};

export {
  $axios,
  fetchPost,
  fetchGet
};
